package com.gxa.utils;

import com.gxa.common.exception.HeaderParamFormatException;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取Header信息
 */
public class HeaderUtils {

    static final String USER_ID = "userID";

    /**
     * 获取请求头中的某个请求头信息，并转为Integer
     *
     * @param request    单次请求
     * @param headerName 请求头信息
     * @return Integer类型的信息
     */
    public static Integer getIntegerRequestHeader(HttpServletRequest request, String headerName) {
        if (request != null) {
            //判断headerName是否为空
            if (headerName != null && !"".equals(headerName)) {
                String header = request.getHeader(headerName);
                try {
                    Integer result = Integer.valueOf(header);
                    return result;
                } catch (NumberFormatException e) {
                    throw new HeaderParamFormatException("数字转换异常！header里面的" + headerName + "是脏东西！");
                }
            } else {
                throw new HeaderParamFormatException("第二个参数不能为空！需要指定获取的Header信息！");
            }
        } else {
            throw new HeaderParamFormatException("request 为空！，没有获取到UserID！");
        }
    }

    /**
     * 直接获取UserID
     *
     * @param httpServletRequest 请求头
     * @return Integer类型的用户ID
     */
    public static Integer getUserID(HttpServletRequest httpServletRequest) {
        return getIntegerRequestHeader(httpServletRequest, USER_ID);
    }
}
